package io.web.bi.es;

import io.web.bi.model.dto.assistant.AssistantDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;

import java.util.List;
import java.util.stream.Collectors;

/**
 * EsTemplateApi.
 *
 * @date 2023-07-24
 */
@SpringBootTest
@Slf4j
public class EsTemplateApi {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Test
    void testEsRestTemplate() {

        // es 起始页为 0
        long current = 0;
        long pageSize = 10;
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 过滤
        boolQueryBuilder.filter(QueryBuilders.termQuery("isDelete", 0));

        String keyword = "springboot";

        // 按关键词检索
        if (StringUtils.isNotBlank(keyword)) {
            boolQueryBuilder.should(QueryBuilders.matchQuery("name", keyword));
            boolQueryBuilder.should(QueryBuilders.matchQuery("goal", keyword));
            boolQueryBuilder.should(QueryBuilders.matchQuery("questionRes", keyword));
            boolQueryBuilder.minimumShouldMatch(1);
        }
        // 排序
        SortBuilder<?> sortBuilder = SortBuilders.scoreSort();
        // 分页
        PageRequest pageRequest = PageRequest.of((int) current, (int) pageSize);
        // 构造查询
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder)
                .withPageable(pageRequest).withSorts(sortBuilder).build();
        SearchHits<AssistantDTO> searchHits = elasticsearchRestTemplate.search(searchQuery, AssistantDTO.class);

        // 查出结果后，从 db 获取最新动态数据（比如点赞数）
        if (searchHits.hasSearchHits()) {
            List<SearchHit<AssistantDTO>> searchHitList = searchHits.getSearchHits();
            // [SearchHit{id='1', score=0.13353139, sortValues=[], content=AssistantDTO(id=1, name=Java集成es, goal=Java集成es, questionRes=Java集成es，使用springboot, userId=null, createTime=null, updateTime=null, isDelete=0), highlightFields={}}]
            System.out.println(searchHitList);
            searchHitList.stream().map(e -> e.getContent().getId()).collect(Collectors.toList()).forEach(System.out::println);
        }
    }
}
